package cn.edu.spark.sql.streaming;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class JavaServerSocket {
    public static void main(String[] args) throws IOException {
        // 创建服务器端Socket，并绑定到指定的端口
        ServerSocket serverSocket = new ServerSocket(8080);

        System.out.println("Server is running and waiting for client connections...");

        while (true) {
            // 监听客户端连接请求，并返回一个新的Socket用于与客户端通信
            Socket clientSocket = serverSocket.accept();

            // 处理客户端请求
            System.out.println("客户端连接： " + clientSocket);
            try {
                handleClientRequest(clientSocket);
            }catch (IOException e) {
                System.out.println("socker die !!!");
            }
        }
    }

    private static void handleClientRequest(Socket clientSocket) throws IOException {
        // 获取客户端Socket的输出流
        OutputStream outputStream = clientSocket.getOutputStream();
        // 创建Scanner对象
        Scanner scanner = new Scanner(System.in);

        // 发送响应给客户端
        while (!clientSocket.isClosed()) {
            String text = scanner.nextLine();
            outputStream.write(text.getBytes());
        }

    }
}
